package ynu.edu.Controller;

import io.github.resilience4j.bulkhead.annotation.Bulkhead;
import io.github.resilience4j.circuitbreaker.annotation.CircuitBreaker;
import io.github.resilience4j.ratelimiter.annotation.RateLimiter;
import jakarta.annotation.Resource;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.web.bind.annotation.*;
import ynu.edu.Entity.PhoneNumber;
import ynu.edu.Entity.User;
import ynu.edu.feign.GetProviderService;

@RestController
@RequestMapping("/number")
public class PhoneController {

    @Resource
    private GetProviderService serviceInstance;

    @GetMapping("/getNumberByUserId/{userId}")
    @LoadBalanced
//    @CircuitBreaker(name = "A",fallbackMethod = "getNumberByUserIDown")
//    @Bulkhead(name = "A", fallbackMethod = "getNumberByUserIDown")
    @RateLimiter(name = "A",fallbackMethod = "getNumberByUserIDown")
    public PhoneNumber getNumberByUserId(@PathVariable("userId") Integer userId){
        PhoneNumber phoneNumber = new PhoneNumber();
        phoneNumber.setPhoneNum("7777-123456789");
        User u =serviceInstance.getUserInfo(userId);
        phoneNumber.setUser(u);
        return phoneNumber;
    }

    public PhoneNumber getNumberByUserIDown(Integer userId, Throwable e){
        System.out.println("获取用户"+userId+"的信息服务当前出现了问题，请稍后再试！"+e);
        return new PhoneNumber();
    }

    @PutMapping("/updateUserName/{newName}")
    @LoadBalanced
    @CircuitBreaker(name = "B",fallbackMethod = "updateUserNameIDown")
    public PhoneNumber updateUserName(@PathVariable("newName") String newName){
        PhoneNumber phoneNumber = new PhoneNumber();
        phoneNumber.setPhoneNum("7777-123456789");
        User updatedUser = serviceInstance.updateUserName(newName);
        phoneNumber.setUser(updatedUser);
        return phoneNumber;
    }

    public PhoneNumber updateUserNameIDown(String newName, Exception e){
        System.out.println("更新用户信息服务当前出现了问题，请稍后再试！");
        return new PhoneNumber();
    }

    @PostMapping("/addUser/{user_id}")
    public PhoneNumber addUser(@PathVariable("user_id") Integer user_id){
        PhoneNumber phoneNumber = new PhoneNumber();
        phoneNumber.setPhoneNum("7777-123456789");
        User newUser = serviceInstance.addUser(user_id);
        phoneNumber.setUser(newUser);
        return phoneNumber;
    }

    @DeleteMapping("/deleteUser/{user_id}")
    public PhoneNumber deleteUser(@PathVariable("user_id") Integer user_id){
        PhoneNumber phoneNumber = new PhoneNumber();
        phoneNumber.setPhoneNum("7777-123456789");
        User u = serviceInstance.deleteUser(user_id);
        phoneNumber.setUser(u);
        return phoneNumber;
    }
}
